//
//  MapViewController.m
//  EDPS
//
//  Created by 张维扬 on 15/12/4.
//  Copyright © 2015年 张维扬. All rights reserved.
//

#import "MapViewController.h"
#import "MANaviAnnotationView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "SharedMapView.h"
@interface MapViewController ()<AMapNaviViewControllerDelegate, UISearchBarDelegate, UITextFieldDelegate>
{
    AMapNaviPoint *_endPoint;
    
    MAUserLocation *_userLocation;
    
    NSMutableArray *_poiAnnotations;
}

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapNaviViewController *naviViewController;
@property (nonatomic, strong) UISearchBar *searchBar;
@end

@implementation MapViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 隐藏back按钮
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.title = @"";
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.toolbar.barStyle          = UIBarStyleDefault;
    self.navigationController.toolbarHidden             = NO;
    
    [self initToolBar];
    
    [self setupMapView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initProperties];
    [self initSearchBar];
    [self initSearch];
    
    [self initNaviManager];
    
    
    [self initMapView];
    
}
- (void)initSearchBar
{
    UIButton *titleView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 20, 30)];
    // 设置为titleView
    self.navigationItem.titleView = titleView;
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 20, 30)];
//    self.searchBar.barStyle     = UIBarStyleBlackOpaque;
    self.searchBar.translucent  = NO;
    self.searchBar.delegate     = self;
    self.searchBar.placeholder  = @"搜索";
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    [titleView addSubview:self.searchBar];
}
#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *key = searchBar.text;
    
    if (_userLocation)
    {
        AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_userLocation.location.coordinate.latitude longitude:_userLocation.location.coordinate.longitude];
        request.keywords            = key;
        request.sortrule            = 1;
        request.requireExtension    = NO;
        
        [self.search AMapPOIAroundSearch:request];
    }
    else
    {
        /* 按下键盘enter, 搜索poi */
        AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
        
        request.keywords         = key;
        request.city             = @"010";
        request.requireExtension = YES;
        [self.search AMapPOIKeywordsSearch:request];
    }
    
    self.searchBar.placeholder = key;
    self.searchBar.delegate = self;
    
    [self.searchBar resignFirstResponder];

    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Initalization

- (void)initToolBar
{
//    UIBarButtonItem *flexbleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    // 返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeSystem];
    back.frame = CGRectMake(0, 0, 20, 20);
    [back setBackgroundImage:[UIImage imageNamed:@"iconfont-popBack"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(popAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backTypeItem = [[UIBarButtonItem alloc] initWithCustomView: back];
    // 返回按钮
    UISwitch *TrafficBtn = [[UISwitch alloc] initWithFrame: CGRectMake(0, 0, 20, 20)];
    [TrafficBtn addTarget:self action:@selector(TrafficBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *TrafficBtnItem = [[UIBarButtonItem alloc] initWithCustomView: TrafficBtn];
    // 分段控制器
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"餐饮", @"酒店",  @"电影", nil]];
    [segmentedControl addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventValueChanged];
    
    UIBarButtonItem *searchTypeItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
    
    self.toolbarItems = [NSArray arrayWithObjects: backTypeItem, searchTypeItem, TrafficBtnItem, nil];
}
- (void)popAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)TrafficBtnAction: (UISwitch *)swi
{
    if (swi.isOn) {
        self.mapView.showTraffic = YES;
    }else{
        self.mapView.showTraffic = NO;
    }
}
#pragma mark - 初始化一个地图
- (void)initMapView
{
    if (_mapView == nil)
    {
        _mapView = [[SharedMapView sharedInstance] mapView];
    }
    
    [_mapView setFrame:self.view.frame];
    [_mapView setDelegate:self];
}
- (void)initNaviManager
{
    if (self.naviManager == nil)
    {
        self.naviManager = [[AMapNaviManager alloc] init];
    }
    
    [self.naviManager setDelegate:self];
}
- (void)initSearch
{
    if (self.search == nil)
    {
        self.search = [[AMapSearchAPI alloc] init];
        self.search.delegate = self;
    }
}
- (void)initProperties
{
    _poiAnnotations = [[NSMutableArray alloc] init];
}
#pragma mark - Handle Views

- (void)setupMapView
{
    [self.mapView setDelegate:self];
    
    [self.mapView setFrame:self.view.bounds];
    [self.view addSubview:self.mapView];
    // 定位
    [self.mapView setShowsUserLocation:YES];
    // 定位用户模式
    self.mapView.userTrackingMode = YES;
    if ([_poiAnnotations count])
    {
        [self showPOIAnnotations];
    }
}
- (void)showPOIAnnotations
{
    [self.mapView addAnnotations:_poiAnnotations];
    
    if (_poiAnnotations.count == 1)
    {
        self.mapView.centerCoordinate = [(MAPointAnnotation *)_poiAnnotations[0] coordinate];
    }
    else
    {
        [self.mapView showAnnotations:_poiAnnotations animated:NO];
    }
}
- (void)cleanMapView
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    [self.mapView setShowsUserLocation:NO];
    
    [self.mapView setDelegate:nil];
} 

#pragma mark - Search

- (void)searchAction:(UISegmentedControl *)segmentedControl
{
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    
    if (_userLocation)
    {
        request.location = [AMapGeoPoint locationWithLatitude:_userLocation.location.coordinate.latitude longitude:_userLocation.location.coordinate.longitude];
    }
    else
    {
        request.location = [AMapGeoPoint locationWithLatitude:39.990459 longitude:116.471476];
    }
    
    request.keywords            = [segmentedControl titleForSegmentAtIndex:segmentedControl.selectedSegmentIndex];
    request.sortrule            = 1;
    request.requireExtension    = NO;
    
    [self.search AMapPOIAroundSearch:request];
}

#pragma mark - Actions

- (void)startEmulatorNavi
{
    [self calculateRoute];
}

- (void)calculateRoute
{
    NSArray *endPoints = @[_endPoint];
    
    [self.naviManager calculateDriveRouteWithEndPoints:endPoints wayPoints:nil drivingStrategy:0];
}

#pragma mark - MapView Delegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (updatingLocation)
    {
        _userLocation = userLocation;
    }
}

- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    if ([view.annotation isKindOfClass:[MAPointAnnotation class]])
    {
        MAPointAnnotation *annotation = (MAPointAnnotation *)view.annotation;
        
        _endPoint = [AMapNaviPoint locationWithLatitude:annotation.coordinate.latitude
                                              longitude:annotation.coordinate.longitude];
        
        [self startEmulatorNavi];
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"poiIdentifier";
        MANaviAnnotationView *annotationView = (MANaviAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[MANaviAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout = YES;
        annotationView.draggable = NO;
        
        return annotationView;
    }
    
    return nil;
}

#pragma mark - Search Delegate

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"SearchError:{%@}", error.localizedDescription);
}
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    
    [self.mapView removeAnnotations:_poiAnnotations];
    [_poiAnnotations removeAllObjects];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        [annotation setCoordinate:CLLocationCoordinate2DMake(obj.location.latitude, obj.location.longitude)];
        [annotation setTitle:obj.name];
        [annotation setSubtitle:obj.address];
        
        [_poiAnnotations addObject:annotation];
    }];
    
    [self showPOIAnnotations];
}


#pragma mark - AMapNaviManager Delegate

- (void)naviManager:(AMapNaviManager *)naviManager error:(NSError *)error
{
    NSLog(@"error:{%@}",error.localizedDescription);
}

- (void)naviManager:(AMapNaviManager *)naviManager didPresentNaviViewController:(UIViewController *)naviViewController
{
    NSLog(@"didPresentNaviViewController");
    
    [self.naviManager startEmulatorNavi];
}

- (void)naviManager:(AMapNaviManager *)naviManager didDismissNaviViewController:(UIViewController *)naviViewController
{
    NSLog(@"didDismissNaviViewController");
    
    [self setupMapView];
}

- (void)naviManagerOnCalculateRouteSuccess:(AMapNaviManager *)naviManager
{
    NSLog(@"OnCalculateRouteSuccess");
    
    if (self.naviViewController == nil)
    {
        [self initNaviViewController];
    }
    
    [self cleanMapView];
    [self.naviManager presentNaviViewController:self.naviViewController animated:YES];
}

- (void)naviManager:(AMapNaviManager *)naviManager onCalculateRouteFailure:(NSError *)error
{
    NSLog(@"onCalculateRouteFailure");
}

- (void)naviManagerNeedRecalculateRouteForYaw:(AMapNaviManager *)naviManager
{
    NSLog(@"NeedReCalculateRouteForYaw");
}

- (void)naviManager:(AMapNaviManager *)naviManager didStartNavi:(AMapNaviMode)naviMode
{
    NSLog(@"didStartNavi");
}

- (void)naviManagerDidEndEmulatorNavi:(AMapNaviManager *)naviManager
{
    NSLog(@"DidEndEmulatorNavi");
}

- (void)naviManagerOnArrivedDestination:(AMapNaviManager *)naviManager
{
    NSLog(@"OnArrivedDestination");
}

- (void)naviManager:(AMapNaviManager *)naviManager onArrivedWayPoint:(int)wayPointIndex
{
    NSLog(@"onArrivedWayPoint");
}

- (void)naviManager:(AMapNaviManager *)naviManager didUpdateNaviLocation:(AMapNaviLocation *)naviLocation
{
    //    NSLog(@"didUpdateNaviLocation");
}

- (void)naviManager:(AMapNaviManager *)naviManager didUpdateNaviInfo:(AMapNaviInfo *)naviInfo
{
    //    NSLog(@"didUpdateNaviInfo");
}

- (BOOL)naviManagerGetSoundPlayState:(AMapNaviManager *)naviManager
{
    return 0;
}

//- (void)naviManager:(AMapNaviManager *)naviManager playNaviSoundString:(NSString *)soundString soundStringType:(AMapNaviSoundType)soundStringType
//{
//    NSLog(@"playNaviSoundString:{%ld:%@}", (long)soundStringType, soundString);
//    
//    if (soundStringType == AMapNaviSoundTypePassedReminder)
//    {
//        //用系统自带的声音做简单例子，播放其他提示音需要另外配置
//        AudioServicesPlaySystemSound(1009);
//    }
//    else
//    {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//            [_iFlySpeechSynthesizer startSpeaking:soundString];
//        });
//    }
//}

- (void)naviManagerDidUpdateTrafficStatuses:(AMapNaviManager *)naviManager
{
    NSLog(@"DidUpdateTrafficStatuses");
}


#pragma mark - AManNaviViewController Delegate

- (void)naviViewControllerCloseButtonClicked:(AMapNaviViewController *)naviViewController
{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
//        [_iFlySpeechSynthesizer stopSpeaking];
//    });
    
    [self.naviManager stopNavi];
    
    [self.naviManager dismissNaviViewControllerAnimated:YES];
}

- (void)naviViewControllerMoreButtonClicked:(AMapNaviViewController *)naviViewController
{
    if (self.naviViewController.viewShowMode == AMapNaviViewShowModeCarNorthDirection)
    {
        self.naviViewController.viewShowMode = AMapNaviViewShowModeMapNorthDirection;
    }
    else
    {
        self.naviViewController.viewShowMode = AMapNaviViewShowModeCarNorthDirection;
    }
}

- (void)naviViewControllerTurnIndicatorViewTapped:(AMapNaviViewController *)naviViewController
{
    [self.naviManager readNaviInfoManual];
}

- (void)initNaviViewController
{
    if (self.naviViewController == nil)
    {
        self.naviViewController = [[AMapNaviViewController alloc] initWithMapView:_mapView delegate:self];
    }
    
    [self.naviViewController setDelegate:self];
}


- (void)viewWillDisappear:(BOOL)animated
{
    self.mapView.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
